<template>
  <div class="mod-share">
    <div v-if="showShare">
      <div class="mod-share-main" id="shareMain">
        <h4 class="mod-share-hd" @mousedown="moveA">
          {{ title }}
          <span class="close" @click="closeShare">
            <i class="iconfont">&#xec47;</i>
            关闭
          </span>
        </h4>
        <div class="mod-share-bd" v-if="!search">
          <div class="share-edit">
            <textarea
              class="share-textarea"
              placeholder="一起聊聊吧~"
              :maxlength="maxLen"
              v-model="txt"
              @input="textareaChange"
            ></textarea>
            <div class="share-song" @click="search = true">
              <div class="share-none" v-if="!set">
                <div class="share-none-l">
                  <i class="iconfont">&#xe8ab;</i>
                </div>
                <h4 class="share-none-tip">给动态配上音乐</h4>
                <span class="share-song-r">
                  <i class="iconfont">&#xe603;</i>
                </span>
              </div>
              <div class="share-set" v-if="set">
                <div class="share-set-l">{{ typeName[typeId] }}：</div>
                <h4 class="share-set-main" v-if="typeId == 0">
                  {{ shareItem.name }} - {{ shareItem.artist }}
                </h4>
                <h4 class="share-set-main" v-if="typeId == 1">
                  {{ shareItem.artist }}
                </h4>
                <h4 class="share-set-main" v-if="typeId == 2">
                  {{ shareItem.name }} - {{ shareItem.artist }}
                </h4>
                <h4 class="share-set-main" v-if="typeId == 3">
                  {{ shareItem.name }} - {{ shareItem.artist }}
                </h4>
                <span class="share-song-r">
                  <i class="el-icon-arrow-right"></i>
                </span>
              </div>
            </div>
          </div>
          <span class="share-edit-count">{{ leftLen }}</span>
          <div class="share-btn">
            <el-button
              type="primary"
              :disabled="edited ? false : true"
              @click="clickShare"
            >
              分享
            </el-button>
            <el-button @click="closeShare">取消</el-button>
          </div>
        </div>
        <div class="mod-share-search" v-if="search">
          <div class="share-search-box">
            <div class="share-search-input">
              <i class="iconfont">&#xec52;</i>
              <input
                type="text"
                v-model="input"
                autofocus
                @input="searchInput"
              />
            </div>
            <ul class="ss-title clearfix">
              <li
                :class="['ss-item', { 'ss-item-current': typeId == index }]"
                v-for="(title, index) in typeName"
                :key="index"
                @click="clickTitle(index)"
              >
                {{ title }}
              </li>
            </ul>
            <div class="ss-result" v-if="found">
              <ul class="ssr-list clearfix" v-if="typeId == 0">
                <li
                  class="ssr-song"
                  v-for="(item, index) in result.songs"
                  :key="index"
                  @click="getItem(item)"
                >
                  <div class="ssr-song-play">
                    <i class="iconfont">&#xe8ca;</i>
                  </div>
                  <div class="ssr-song-name">{{ item.name }}</div>
                  <div class="ssr-song-artist">
                    {{ item.ar | getArtist }}
                  </div>
                </li>
              </ul>
              <ul class="ssr-list clearfix" v-if="typeId == 1">
                <li
                  class="ssr-artist"
                  v-for="(item, index) in result.artists"
                  :key="index"
                  @click="getItem(item)"
                >
                  <div class="ssr-artist-l">
                    <img class="ssr-artist-pic" :src="item.img1v1Url" alt="" />
                  </div>
                  <div class="ssr-artist-name">
                    {{ item.name }}
                  </div>
                </li>
              </ul>
              <ul class="ssr-list clearfix" v-if="typeId == 2">
                <li
                  class="ssr-album"
                  v-for="(item, index) in result.albums"
                  :key="index"
                  @click="getItem(item)"
                >
                  <div class="ssr-album-l">
                    <img class="ssr-album-pic" :src="item.picUrl" alt="" />
                  </div>
                  <div class="ssr-album-name">
                    {{ item.name }}
                  </div>
                  <div class="ssr-album-artist">
                    {{ item.artists | getArtist }}
                  </div>
                </li>
              </ul>
              <ul class="ssr-list clearfix" v-if="typeId == 3">
                <li
                  class="ssr-playlist"
                  v-for="(item, index) in result.playlists"
                  :key="index"
                  @click="getItem(item)"
                >
                  <div class="ssr-playlist-l">
                    <img
                      class="ssr-playlist-pic"
                      :src="item.coverImgUrl"
                      alt=""
                    />
                  </div>
                  <div class="ssr-playlist-name">
                    {{ item.name }}
                  </div>
                  <div class="ssr-playlist-creator">
                    by {{ item.creator.nickname }}
                  </div>
                </li>
              </ul>
            </div>
            <div
              class="ss-not-found"
              v-if="!found && input.trimLeft().length > 0"
            >
              很抱歉，未能找到相关搜索结果
            </div>
          </div>
          <div class="share-btn">
            <el-button type="primary" @click="backEdit">返回</el-button>
          </div>
        </div>
      </div>
    </div>
    <tip
      v-if="showTip"
      tipMessage="是否退出本次编辑?"
      btnY="退出"
      @clickSure="clickSure"
      @closeTip="showTip = false"
    ></tip>
    <small-tip :tipMessage="smallTipMsg" v-if="showSmallTip"></small-tip>
  </div>
</template>

<script>
import Tip from "components/tip/Tip";
import SmallTip from "components/tip/SmallTip";
export default {
  components: {
    Tip,
    SmallTip,
  },
  data() {
    return {
      title: "分享",
      typeId: 0,
      type: ["song", "artist", "album", "playlist"],
      typeKey: ["1", "100", "10", "1000"],
      typeName: ["单曲", "歌手", "专辑", "歌单"],
      showShare: true,
      // 分享按钮
      edited: false,
      // 搜索歌曲、歌单分享
      search: false,
      // 有没有分享歌曲、歌手。。。
      set: false,
      // 最大字符数
      maxLen: 140,
      // 还能输入的字符数
      leftLen: 140,
      // 分享文本
      txt: "",
      // 搜索
      input: "",
      // 输入防抖
      timeout: null,
      // 搜索结果
      result: [],
      found: true,
      // 要分享的东西
      shareItem: {},
      // 提示
      showTip: false,
      showSmallTip: false,
      smallTipMsg: "操作提示",
    };
  },
  filters: {
    getArtist(value) {
      if (value.length == 1) {
        return value[0].name;
      } else {
        let art = [];
        value.forEach((item) => {
          art[art.length] = item.name;
        });
        return art.join("/");
      }
    },
  },
  mounted() {
    this.setTop();
    this.shareItem = this.$store.state.shareItem;
    if (this.shareItem.id) {
      this.set = true;
      this.edited = true;
      this.typeId = this.type.indexOf(this.shareItem.type);
      // console.log(this.typeId);
    }
  },
  methods: {
    clickShare() {
      let ti = "";
      if (this.shareItem.id) {
        ti = "&id=" + this.shareItem.id + "&type=" + this.shareItem.type;
      } else {
        ti = "&type=noresource";
      }
      this.axios({
        url: "/share/resource?msg=" + this.txt + ti,
      })
        .then((res) => {
          console.log(res);
          this.smallTipMsg = "分享动态成功！";
          this.showSmallTip = true;
          this.showShare = false;
          setTimeout(() => {
            this.showSmallTip = false;
            this.$store.commit("changeShowShare", false);
            this.$store.commit("changeShareItem", {});
          }, 1000);
          if (this.$route.path == "/friend") {
            this.$router.go(0);
          }
        })
        .catch((err) => {
          console.log(err);
          this.smallTipMsg = "分享动态失败！";
          this.showSmallTip = true;
          setTimeout(() => {
            this.showSmallTip = false;
          }, 1000);
        });
    },
    getItem(item) {
      let newItem = {
        id: item.id,
        type: this.type[this.typeId],
        name: item.name,
      };
      switch (this.typeId) {
        case 0:
          newItem.artist = this.$options.filters["getArtist"](item.ar);
          break;
        case 2:
          newItem.artist = this.$options.filters["getArtist"](item.artists);
          break;
        case 3:
          newItem.artist = item.creator.nickname;
          break;
      }
      // console.log(newItem);
      this.$store.commit("changeShareItem", newItem);
      // console.log(this.$store.state.shareItem);
      this.shareItem = newItem;
      this.search = false;
      this.set = true;
    },
    backEdit() {
      this.search = false;
    },
    searchInput() {
      // 防抖
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        if (this.input.trimLeft().length > 0) {
          this.getSearch();
        }
      }, 500);
    },
    getSearch() {
      this.axios({
        url:
          "/cloudsearch?type=" +
          this.typeKey[this.typeId] +
          "&keywords=" +
          this.input.trimLeft(),
      })
        .then((res) => {
          let foundTimer = null;
          if (
            !res.data.result ||
            res.data.code == 400 ||
            (!res.data.result.songs &&
              !res.data.result.artists &&
              !res.data.result.albums &&
              !res.data.result.playlists)
          ) {
            foundTimer = setTimeout(() => {
              this.found = false;
              console.log(this.found);
            }, 1000);
          } else {
            clearTimeout(foundTimer);
            this.result = res.data.result;
            this.found = true;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    clickTitle(id) {
      this.typeId = id;
      this.getSearch();
    },
    textareaChange() {
      if (this.txt.trimLeft().length > 0) {
        this.edited = true;
      }
      // 输入框的字符数
      // console.log(e);
      // console.log(e.target.value);
      // console.log(this.txt);
      // 字母数字占0.5个中文
      var repOne = /[0-9a-zA-Z\s]/;
      // 如果split 分割后，换行符会 根其他字符 粘合在一起 例如 ('ab\nc').split('') = ['a','b\n','c']
      // var repEnter = /[\&]/; //  & 符号
      // 用& 代替 换行符
      // let str = this.txt.replace(/[\r\n]/g, "&");
      // 初始剩余可输入字符数
      var totalLen = 140;
      // 设置maxLen
      var maxLen = 140;
      // 对字符串 分割成数组
      var strAttr = this.txt.split("");
      // 已输入字符数
      var len = 0;
      // 删除退格 为空时返回
      if (strAttr.length == 0) {
        this.leftLen = totalLen;
        this.maxLen = maxLen;
      } else {
        strAttr.forEach(function (val, key) {
          // 字母数字空格
          if (repOne.test(val)) {
            len += 0.5; // 统计 占位0.5个中文
            maxLen += 0.5; // 最多输入增加 0.5个中文
          }
          // 换行符  不占位 len 不增加
          // 检测 &
          else {
            // 中文或者语言其他符号
            len++; // 占位 1个中文
          }
        });
        this.leftLen = Math.ceil(totalLen - len); // 剩余可输入字符 向下取 页面显示 剩余字符
        this.maxLen = Math.ceil(maxLen); // 向上取 textarea最大字符
      }
      // console.log(this.txt);
      // console.log(this.maxLen);
    },
    clickSure() {
      this.showShare = false;
      this.$store.commit("changeShowShare", false);
      this.$store.commit("changeShareItem", {});
      console.log(this.$store.state.showShare);
    },
    closeShare() {
      if (this.txt.trimLeft().length > 0 || this.shareItem.id) {
        this.showTip = true;
      } else {
        this.showShare = false;
        this.$store.commit("changeShowShare", false);
        this.$store.commit("changeShareItem", {});
        console.log(this.$store.state.showShare);
      }
    },
    setTop() {
      // topH 卷上去的高度
      let topH =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop;
      // documentHeight 为可视窗口的高度
      let documentHeight = document.documentElement.clientHeight;
      this.h = Math.floor(topH + documentHeight / 2);
      let mcm = document.querySelector(".mod-share-main");
      mcm.style.top = this.h - 200 + "px";
    },
    moveA(e) {
      let el = document.getElementById("shareMain");
      e = e || window.event;
      // 鼠标到myAdd的距离
      var disX = e.clientX - el.offsetLeft;
      var disY = e.clientY - el.offsetTop;
      document.onmousemove = function (e) {
        var l = e.clientX - disX;
        var t = e.clientY - disY;
        if (l <= 250) {
          el.style.left = "250px";
        } else if (l + 250 >= document.body.clientWidth) {
          el.style.left =
            document.body.clientWidth - 8 - el.offsetWidth / 2 + "px";
        } else {
          el.style.left = l + "px";
        }
        if (t <= 0) {
          el.style.top = "0px";
        } else if (t >= document.body.clientHeight - el.offsetHeight) {
          el.style.top = document.body.clientHeight - el.offsetTop - +"px";
        } else {
          el.style.top = t + "px";
        }
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      };
    },
  },
};
</script>

<style>
.mod-share {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1010;
}
.mod-share-main {
  position: absolute;
  left: 50vw;
  transform: translateX(-50%);
  width: 530px;
  background-color: var(--color-theme-light-5);
  border-radius: 10px;
  box-shadow: 0 0 10px 3px #999;
  overflow: hidden;
  z-index: 105;
}
.mod-share-hd {
  padding: 0 10px 0 20px;
  height: 40px;
  line-height: 40px;
  font-weight: 400;
  font-size: 20px;
  color: #f2f2f2;
  background-color: var(--color-theme);
  cursor: move;
}
.mod-share-hd .close {
  position: absolute;
  right: 5px;
  width: 30px;
  height: 30px;
  text-align: center;
  font-size: 0;
  cursor: pointer;
}
.mod-share-hd .close .iconfont {
  font-size: 16px;
}
/* mod-share-bd */
.mod-share-bd {
  position: relative;
  margin: 20px 30px;
  height: 270px;
}
.share-edit {
  width: 100%;
  height: 200px;
  border: 1px solid #ccc;
  overflow: hidden;
}
.share-textarea {
  padding: 5px;
  width: 100%;
  height: 140px;
  background-color: transparent;
  border: none;
  outline: none;
  resize: none;
  overflow: auto;
}
.share-song {
  position: relative;
  margin: 4px;
  padding: 6px 0;
  width: 460px;
  border-top: 1px solid #ccc;
  overflow: hidden;
  cursor: pointer;
}
.share-none,
.share-set {
  width: 100%;
  height: 40px;
  line-height: 40px;
  overflow: hidden;
}
.share-none-l {
  float: left;
  width: 40px;
  height: 40px;
  border-radius: 5px;
  background-color: var(--color-theme);
  overflow: hidden;
}
.share-none-l i {
  margin-left: 8px;
  font-size: 20px;
  color: #fff;
}
.share-none-tip,
.share-set-main {
  display: inline-block;
  margin-left: 10px;
  width: 380px;
  font-weight: 400;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.share-song-r {
  display: inline-block;
  position: absolute;
  top: 6px;
  right: 10px;
}
.share-set-l {
  float: left;
  height: 40px;
}
.share-edit-count {
  position: absolute;
  top: 205px;
  right: 10px;
  font-size: 14px;
  color: #999;
}
.share-btn {
  margin-top: 30px;
  display: flex;
  justify-content: space-evenly;
}
/* mod-share-search */
.mod-share-search {
  position: relative;
  margin: 20px 30px;
  height: 360px;
}
.share-search-box {
  margin-bottom: -10px;
  width: 100%;
  height: 300px;
  border: 1px solid #ccc;
  overflow: hidden;
}
.share-search-input {
  position: relative;
  padding-left: 40px;
  width: 100%;
  height: 40px;
}
.share-search-input i {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 20px;
}
.share-search-input input {
  display: inline-block;
  width: 400px;
  height: 40px;
  border: none;
  outline: none;
  background-color: transparent;
}
.ss-title {
  position: relative;
  width: 100%;
  height: 30px;
  line-height: 28px;
  overflow: hidden;
}
.ss-item {
  float: left;
  width: 25%;
  font-size: 14px;
  text-align: center;
  border-top: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  cursor: pointer;
}
.ss-item:last-child {
  border-right: none;
}
.ss-item-current {
  border-top: 2px solid var(--color-theme);
  border-bottom: none;
}
.ss-result {
  width: 100%;
  height: 228px;
  overflow-x: hidden;
  overflow-y: auto;
}
.ssr-song,
.ssr-artist,
.ssr-album,
.ssr-playlist {
  font-size: 14px;
  background-color: var(--color-theme-light-5);
  cursor: pointer;
}
.ssr-song:hover,
.ssr-artist:hover,
.ssr-album:hover,
.ssr-playlist:hover {
  background-color: rgba(0, 0, 0, 0.1) !important;
}
.ssr-song:nth-child(even),
.ssr-artist:nth-child(even),
.ssr-album:nth-child(even),
.ssr-playlist:nth-child(even) {
  background-color: var(--color-theme-light-4);
}
.ssr-song {
  padding: 0 5px;
  width: 100%;
  height: 30px;
  line-height: 30px;
}
.ssr-song-play {
  float: left;
  width: 40px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  overflow: hidden;
}
.ssr-song-play .iconfont {
  font-size: 14px;
}
.ssr-song-name,
.ssr-song-artist {
  float: left;
  height: 30px;
  line-height: 30px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ssr-song-name {
  margin-right: 10px;
  width: 250px;
}
.ssr-song-artist {
  width: 150px;
}
/* ssr-artist */
.ssr-artist,
.ssr-album,
.ssr-playlist {
  padding: 10px;
  width: 100%;
  height: 60px;
}
.ssr-artist-l,
.ssr-album-l,
.ssr-playlist-l {
  float: left;
  margin-right: 10px;
  width: 40px;
  height: 40px;
}
.ssr-artist-pic,
.ssr-album-pic,
.ssr-playlist-pic {
  width: 40px;
  height: 40px;
}
.ssr-artist-name {
  float: left;
  width: 380px;
  height: 40px;
  line-height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ssr-album-name,
.ssr-album-artist,
.ssr-playlist-name,
.ssr-playlist-creator {
  float: left;
  height: 40px;
  line-height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ssr-album-name,
.ssr-playlist-name {
  margin-right: 10px;
  width: 240px;
}
.ssr-album-artist,
.ssr-playlist-creator {
  width: 140px;
}

.ss-not-found {
  margin-top: 104px;
  height: 20px;
  line-height: 20px;
  font-size: 12px;
  text-align: center;
}
</style>